/**
 * 
 */
package com.walle.springinpractice.ch01.dao.csv;

import java.io.BufferedReader;
import java.io.FileReader;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import org.springframework.core.io.Resource;

import com.walle.springinpractice.ch01.dao.AccountDao;
import com.walle.springinpractice.ch01.model.Account;

/**
 * @author <a href="mailto:wallellen@hotmail.com">Walle</a>
 * 
 *         2014年1月23日
 */
public class CsvAccountDao implements AccountDao {

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.walle.springinpractice.ch01.dao.AccountDao#listAll()
	 */
	public List<Account> listAll() throws Exception {
		List<Account> accounts = new ArrayList<Account>();
		BufferedReader reader = new BufferedReader(new FileReader(
				resource.getFile()));
		SimpleDateFormat format = new SimpleDateFormat("MMddyyyy");

		String line = null;
		Account account = null;
		String[] values = null;

		while ((line = reader.readLine()) != null) {
			values = line.split(",");
			account = new Account();
			account.setAccountNo(values[0]);
			account.setBalance(new BigDecimal(values[1]));
			account.setLastPaidOn(format.parse(values[2]));
			accounts.add(account);
		}

		reader.close();

		return accounts;
	}

	public void setResource(Resource resource) {
		this.resource = resource;
	}

	private Resource resource;
}
